<template>
    <view class="progress-box">
        <progress :percent="degree" show-info stroke-width="10" />
    </view>
    <!-- swiper区域，将realQuestions渲染 -->
    <swiper class="swiper-container" :current="swiperCurrent">
        <swiper-item v-for="question in realQuestions" :key="question.id">
            <view class="topic-area">
                <!-- 根据type动态切换class -->
                <text
                    class="question-type"
                    :class="{
                        'question-type-radio': question.type === 1,
                        'question-type-select': question.type === 2,
                        'question-type-judge': question.type === 3
                    }"
                >{{ question.typeName }}</text>
                <text class="question-content">{{ question.content }}</text>
            </view>
            <view class="image-area" v-if="question.image!=''">
                <image :src="question.image" style="width: 100px; height: 100px;" />
            </view>
            <view class="option-area">
                <view class="option-item" v-for="opt in question.options" :key="opt.id" @click="toggleOptionLetter(question.id, opt.id)">
                    <text
                        class="option-letter"
                        :class="opt.checked === 1 ? 'option-letter-color-checked' : 'option-letter-color-default'"
                    >{{ opt.label }}</text>
                    <text>{{ opt.text }}</text>
                </view>
            </view>
            <view class="answer-area" v-if="viewOnly  && realQuestions.find(a => a.id === question.id)">
                <text>答案：</text>
                <text>{{ realQuestions.find(a => a.id === question.id)?.answer }}</text>
            </view>
            <view class="analysis-area" v-if="viewOnly  && realQuestions.find(e => e.id === question.id)">
                <view class="analysis-title">
                    <text></text>
                    <text style="font-weight: bolder;">解析：</text>
                </view>
                <text>{{ realQuestions.find(e => e.id === question.id)?.analysis }}</text>
            </view>
            <view class="next-btn">
                <button size="mini" type="primary">下一题</button>
            </view>
        </swiper-item>
    </swiper>

    <!-- 提交答卷的盒子 -->
    <view class="submit-box">
        <view @click="submitExam" v-if="!viewOnly" class="submit-btn">
            <text>交卷</text>
            <text>{{ formattedTime }}</text>
        </view>
        <view @click="openQuestionCard" class="question-card-btn">
            <view>
                <text>{{ unanswered }}/{{ totalQuestions }}</text>
                <text>未答</text>
            </view>
            <view>
                <text>{{ correct }}</text>
                <text>答对</text>
            </view>
            <view>
                <text>{{ wrong }}</text>
                <text>答错</text>
            </view>
        </view>
    </view>

    <!-- uni-popup 弹窗，用于展示答题卡概况 -->
    <view>
        <!-- 普通弹窗 -->
        <uni-popup ref="popup" type="bottom" background-color="#fff">
            <view class="popup-content" >
                <!-- 遍历 realQuestions 将序号展示在这里 -->
                <view
                        v-for="(question, index) in realQuestions"
                        :key="question.id"
                        class="popup-question-card"
                        :class="question.options && question.options.some(opt => opt.checked === 1) ? 'card-color-answered' : 'card-color-default'"
                        @click="selectQuestion(index)"
                        >
                    <text>{{ index + 1 }}</text>
                </view>
            </view>
        </uni-popup>
    </view>
    <uni-popup ref="popupSubmit" type="center" background-color="transparent" :custom-style="'background:transparent;box-shadow:none;'">
        <view class="popup-submit" style="background:#fff;">
            <view class="popup-submit-title" >
                <text>确认交卷</text>
            </view>
            <view class="popup-submit-content" >
                <!-- 展示未答题数和剩余时间 -->
                <view>
                    <text>{{ unanswered }}/{{ totalQuestions }}</text>
                    <text>未答</text>
                </view>
                <view>
                    <text>{{ formattedTime }}</text>
                    <text>剩余时间</text>
                </view>
            </view>
            <view class="popup-submit-btn">
                <button size="mini" type="primary" @click="submitExamReal" :loading="loading">确认交卷</button>
                <button size="mini" type="default" @click="popupSubmit.close()">取消</button>
            </view>
        </view>
    </uni-popup>
</template>

<script setup>
    import { requestPostJson } from '@/api/request';
    import { onUnload } from '@dcloudio/uni-app';
    import { ref, computed, watch } from 'vue';
     // 进入页面时获取examId并请求试题
    import { onLoad } from '@dcloudio/uni-app';
    import { requestGet, pathQuestionById } from '@/api/request';

    const examId = ref(0);
    const viewOnly = ref(false); // 是否是查看模式
    const realQuestions = ref([]); // 真实的试题数据

    onLoad(async (option) => {
        examId.value = parseInt(option.examId, 10);
        console.log('exam页面获取到的examId:', examId.value);
        viewOnly.value = option.viewOnly === 'true'; // 如果传递了 viewOnly 参数且为 'true' 则为查看模式
        console.log('viewOnly=', viewOnly.value);
        if (!examId.value) {
            uni.showToast({
                title: '参数异常',
                duration: 2000,
                icon: 'error'
            });
            setTimeout(() => {
                uni.navigateBack();
            }, 1500);
            return;
        }
        try {
            const res = await requestGet(pathQuestionById, {examId: examId.value, viewOnly: viewOnly.value ? 1 : 0 });
            if (res && res.code === 0 && Array.isArray(res.data.list)) {
                realQuestions.value = res.data.list;
                totalQuestions.value = res.data.list.length;
                unanswered.value = res.data.list.length; // 初始时未答题数等于总题数
                // 这里可以根据实际情况计算 correct 和 wrong
                correct.value = 0; // 初始时答对数为0
                wrong.value = 0; // 初始时答错数为0
                // 倒计时依赖 res.data.metrics.leftTime
                leftTime.value = res.data.metric.leftTime;

                console.log(realQuestions.value);
            } else {
                uni.showToast({
                    title: '获取试题失败',
                    duration: 2000,
                    icon: 'error'
                });
            }
        } catch (err) {
            console.log('获取试题服务异常:', err);
            uni.showToast({
                title: '服务异常',
                duration: 2000,
                icon: 'error'
            });
        }
    });

    // 页面需要的一些响应式变量
    const loading = ref(false);

    const degree = ref(50);
    const leftTime = ref(2700); // 45分钟，单位是秒
    const totalQuestions = ref(0);
    const unanswered = ref(0);
    const correct = ref(0);
    const wrong = ref(0);

    const swiperCurrent = ref(0); // 当前swiper的索引

    // !+ [统计]
    // 根据leftTime计算倒计时显示的字符串
    // 这里可以使用计算属性
    const formattedTime = computed(() => {
        const minutes = Math.floor(leftTime.value / 60);
        const seconds = leftTime.value % 60;
        return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    });

    // leftTime每秒减1，倒计时到0时清除定时器
    let timer = null;
    timer = setInterval(() => {
        if (leftTime.value > 0) {
            leftTime.value--;
            if (leftTime.value === 0) {
                clearInterval(timer);
                timer = null;
            }
        }
    }, 1000);

    // 页面卸载时清除定时器（uni-app写法）
    onUnload(() => {
        if (timer) {
            clearInterval(timer);
            timer = null;
        }
    });
    // !- [统计]


    // !+ [swiper区域]
    // 模拟一些试题数据
    const demoRealQuestions = ref([
        {
            id: 1,
            type: 1,
            typeName: '单选',
            content: '特仑苏牛奶的商标是？',
            image: '/static/logo.png',
            checked: 1, // 0表示未选中，1表示选中
            options: [
                { label: 'A', text: '特仑苏' },
                { label: 'B', text: '蒙牛' },
                { label: 'C', text: '伊利' },
                { label: 'D', text: '三元' },
            ],
            answer: 'A', // 正确答案
            userSelected: [], // 用户选择的答案-单选一个，多选多个，判断一个
            analysis: '这个标志表示前方是易滑路面，车辆在此路段行驶时要注意慢行，防止打滑。这个标志表示前方是易滑路面，车辆在此路段行驶时要注意慢行，防止打滑。这个标志表示前方是易滑路面，车辆在此路段行驶时要注意慢行，防止打滑。',
        },
        {
            id: 2,
            type: 2,
            typeName: '多选',
            content: '以下哪些城市曾经是中国的首都？',
            image: '',
            options: [
                { label: 'A', text: '北京' },
                { label: 'B', text: '南京' },
                { label: 'C', text: '西安' },
                { label: 'D', text: '洛阳' },
                { label: 'E', text: '成都' },
            ],
            answer: 'A,C',
            analysis: '这个标志表示前方是易滑路面，车辆在此路段行驶时要注意慢行，防止打滑。这个标志表示前方是易滑路面，车辆在此路段行驶时要注意慢行，防止打滑。这个标志表示前方是易滑路面，车辆在此路段行驶时要注意慢行，防止打滑。',
        },
        {
            id: 3,
            type: 3,
            typeName: '判断',
            content: '秦始皇是中国历史上第一个皇帝，对吗？',
            image: '',
            options: [
                { label: 'A', text: '正确' },
                { label: 'B', text: '错误' },
            ],
            answer: 'A',
            analysis: '这个标志表示前方是易滑路面，车辆在此路段行驶时要注意慢行，防止打滑。这个标志表示前方是易滑路面，车辆在此路段行驶时要注意慢行，防止打滑。这个标志表示前方是易滑路面，车辆在此路段行驶时要注意慢行，防止打滑。',
        }
    ]);
    // 监听 realQuestions 的变化，更新 unanswered
    watch(realQuestions, (newItem) => {
        unanswered.value = newItem.filter(q => !q.userSelected || q.userSelected.length === 0).length;
        // 进度条 deep
        degree.value = Math.floor((totalQuestions.value - unanswered.value) / totalQuestions.value * 100);
    }, { deep: true });

    // !- [swiper区域]

    // 切换option-letter样式
    function toggleOptionLetter(questionId, optionId) {
        console.log('点击了questionId=', questionId, '的optionId=', optionId);
        // 找到对应的题目
        const question = realQuestions.value.find(q => q.id === questionId);
        if (!question) return;
        // 找到对应的选项
        const option = question.options.find(o => o.id === optionId);
        if (!option) return;
        // 切换选项的checked状态
        if (question.type === 1 || question.type === 3) {
            // 单选或判断题，选中一个，其他都不选
            question.options.forEach(o => {
                o.checked = (o.id === optionId) ? 1 : 0;
            });
            // 把选中的答案更新到 question.userSelected
            question.userSelected = [option.label];
        } else if (question.type === 2) {
            // 多选题，切换当前选项的状态
            option.checked = option.checked === 1 ? 0 : 1;
            // 把选中的答案更新到 question.userSelected
            const selectedOptions = question.options.filter(o => o.checked === 1).map(o => o.label);
            question.userSelected = selectedOptions;
        }

    }

    // 打开答题卡
    const popup = ref(null); // 引用 uni-popup 组件, ref='popup'
    function openQuestionCard() {
        console.log('打开答题卡');
        console.log(realQuestions.value);
        popup.value && popup.value.open();
    }
    // 选择某个题目
    function selectQuestion(index) {
        console.log('选择了第', index + 1, '题');
        popup.value && popup.value.close();
        // 跳转到对应的swiper-item
        swiperCurrent.value = index;
    }

    // 交卷
    const popupSubmit = ref(null); // 引用 uni-popup 组件, ref='popupSubmit'
    function submitExam() {
        console.log('交卷');
        // 这里可以添加交卷的逻辑，比如计算分数，提交到后端等
        popupSubmit.value && popupSubmit.value.open();
    }

    function submitExamReal() {
        console.log('确认交卷');
        popupSubmit.value && popupSubmit.value.close();
        loading.value = true;

        // 过滤 realQuestions，找出已作答的题目
        const answeredQuestions = realQuestions.value.filter(q => q.userSelected && q.userSelected.length > 0);
        console.log('已作答的题目:', answeredQuestions);
        // 只保留 id 和 userSelected 字段
        const filteredAnswers = answeredQuestions.map(q => ({ id: q.id, userSelected: q.userSelected }));
        console.log('过滤后的答案:', filteredAnswers);

        // 提交试卷到后端
        requestPostJson('/exam/submit', {
            examId: examId.value,
            answer: filteredAnswers // 使用过滤后的答案
        }).then(res => {
            loading.value = false;
            if (res && res.code === 0 && res.data) {
                // 展示弹窗结果
                uni.showModal({
                    title: '成绩统计',
                    content: `总题数：${res.data.total}；答对：${res.data.correct}；答错：${res.data.wrong}；未答：${res.data.unanswered}`,
                    showCancel: false,
                    success: () => {
                        uni.switchTab({
                           url: `/pages/exampage/result`
                        });
                    }
                });
            } else {
                uni.showToast({
                    title: '提交失败',
                    icon: 'error',
                    duration: 2000
                });
            }
        }).catch(() => {
            loading.value = false;
            uni.showToast({
                title: '服务异常',
                icon: 'error',
                duration: 2000
            });
        });
        popupSubmit.value && popupSubmit.value.close();
        
    }

</script>

<style scoped>
    .progress-box {
        margin: 20px;
    }
    /* swiper-container 能够自适应屏幕高度 */
    .swiper-container {
        height: calc(100vh - 150px);
    }
    .swiper-container swiper-item {
        /* 当内容超过了容器高度时，允许滚动 */
        overflow-y: auto;
    }
    .topic-area {
        padding: 20px;
    }
    .question-type {
        font-weight: bold;
        font-size: 20rpx;
        /* 文字设置为白色，圆角，padding */
        color: white;
        border-radius: 10rpx;
        padding: 8rpx 15rpx;
    }
    .question-type-radio {
        background-color: rgb(5, 138, 5);
    }
    .question-type-select {
        background-color: rgb(9, 25, 135);
    }
    .question-type-judge {
        background-color: rgb(6, 157, 165);
    }

    .question-content {
        padding-left: 20rpx;
        margin-bottom: 10px;
        font-size: 32rpx;
    }
    .image-area {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 10px;
    }
    .option-area {
        margin-top: 20px;
        padding: 0 20px;
    }
    .option-item {
        background-color: #f0f0f0;
        border-radius: 10rpx;
        padding: 15rpx;
        margin-bottom: 15rpx;
        font-size: 28rpx;
    }

    /* option-letter 默认样式包含为一个圆框，字体居中 */
    .option-letter {
        display: inline-block;
        width: 50rpx;
        height: 50rpx;
        line-height: 50rpx;
        border-radius: 50%;
        background-color: #fff;
        text-align: center;
        margin-right: 10rpx;
    }

    .option-letter-color-default {
        background-color: #fff;
        color: #000;
    }

    .option-letter-color-checked {
        background-color: hsl(125, 90%, 58%);
        color: #fff;
    }

    /* option-letter 选中样式，背景改为 深灰色即可 */
    .option-letter-selected {
        display: inline-block;
        width: 50rpx;
        height: 50rpx;
        line-height: 50rpx;
        border-radius: 50%;
        background-color: #6d6969;
        text-align: center;
        margin-right: 10rpx;
    }

    /* answer-area 容器，背景为浅绿色，圆角，padding */
    .answer-area {
        background-color: #e0f7e0;
        border-radius: 10rpx;
        padding: 15rpx 20rpx;
        margin: 20px;
        font-size: 28rpx;
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }

    /* next-btn 容器，按钮居中 */
    .next-btn {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 30px;
    }

    /* analysis-area 容器，背景为浅黄色，圆角，padding，内部两个view并排展示 */
    .analysis-area {
        background-color: #fff4e5;
        border-radius: 10rpx;
        padding: 15rpx 20rpx;
        margin: 20px;
        font-size: 28rpx;
        display: flex;
        flex-direction: column; /* 让子元素垂直排列 */
        justify-content: flex-start;
        align-items: flex-start;
    }

    /* analysis-title 容器，第一个text是一个空的盒子有一定的宽度，并且有一个绿色的背景颜色，这个盒子是圆角的 */
    .analysis-title {
        display: flex;
        align-items: center;
        margin-bottom: 10rpx;
    }
    .analysis-title text:first-child {
        border-radius: 5%;
        display: inline-block;
        width: 10rpx;
        height: 50rpx;
        background-color: #5cb85c;
        margin-right: 10rpx;
        line-height: 50rpx;
        text-align: center;
        color: white;
    }

    /* submit-box 容器，固定在页面底部，宽度100%，高度100rpx，背景颜色为白色，padding 0 20rpx，盒子内部只有一行分为左右两个view，左边是交卷按钮+倒计时在一个绿色背景圆角的容器之中，右边是三个小盒子并排展示，每个小盒子都是数字text在上，文字text在下 */
    .submit-box {
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 150rpx;
        background-color: white;
        padding: 0 20rpx;
        display: flex;
        justify-content: space-evenly; /* 左右均分 */
        align-items: center; /* 垂直居中 */
        box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1); /* 上边框阴影 */
    }
    .submit-box .submit-btn {
        background-color: #5cb85c;
        border-radius: 50rpx;
        padding: 10rpx 20rpx;
        color: white;
        font-size: 28rpx;
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }
    .submit-box .submit-btn text:first-child {
        margin-right: 20rpx;
    }
    .submit-box .question-card-btn {
        display: flex;
        justify-content: space-evenly;
        align-items: center;
        width: 60%;
    }
    .submit-box .question-card-btn > view {
        display: flex;
        flex-direction: column; /* 让子元素垂直排列 */
        justify-content: center;
        align-items: center;
    }
    .submit-box .question-card-btn > view text:first-child {
        font-size: 28rpx;
        font-weight: bold;
    }
    .submit-box .question-card-btn > view text:last-child {
        font-size: 24rpx;
        color: #666;
    }

    /* popup-content 容器，内部有多个 question-card 容器是一个圆形*/
    .popup-content {
        padding: 20rpx;
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        gap: 20rpx;
    }

    .popup-question-card {
        width: 80rpx;
        height: 80rpx;
        line-height: 80rpx;
        text-align: center;
        border: 1px solid #ccc;
        border-radius: 50%;
        margin: 0;
        flex: none;
    }

    .card-color-default {
        background-color: #fff;
        color: #000;
    }
    .card-color-answered {
        background-color: hsl(125, 90%, 58%);
        color: #fff;
    }


    /* 提交弹窗分为三部分 popup-submit-title popup-submit-content popup-submit-btn */
    .popup-submit {
        width: 100%;
        margin: 0 auto;
        border-radius: 25rpx;
        overflow: hidden; /* 防止圆角被内容撑破 */
        box-sizing: border-box;
        width:80vw;
        max-width:600px;
    }
    /* popup-submit-title 容器，文字加粗，居中 */
    .popup-submit-title {
        padding: 20rpx;
        text-align: center;
        font-weight: bold;
    }

    /* popup-submit-content 容器，其下的两个view并排展示，每个view中两个text分两行展示 */
    .popup-submit-content {
        padding: 20rpx;
        display: flex;
        justify-content: space-evenly;
        align-items: center;
    }
    .popup-submit-content > view {
        display: flex;
        flex-direction: column; /* 让子元素垂直排列 */
        justify-content: center;
        align-items: center;
    }
    .popup-submit-content > view text:first-child {
        font-size: 28rpx;
        font-weight: bold;
    }
    .popup-submit-content > view text:last-child {
        font-size: 24rpx;   
        color: #666;
    }

    /* popup-submit-btn 容器，里面有两个按钮, 左右排列，而且各自占50%的宽度，且增加圆角形成按钮的效果 */
    .popup-submit-btn {
        padding: 20rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .popup-submit-btn button {
        width: 48%;
        border-radius: 30rpx;
        border: #000 1px solid;
    }
</style>